package com.jd.dlc.limit.biz;

import com.jd.dlc.domain.WrapLimiterRule;
import com.jd.dlc.limit.Trigger;
import com.jd.dlc.limit.cache.LimiterRecord;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: dlc
 * @ClassName WindActurtor
 * @description:
 * @author: sizegang
 * @create: 2022-06-11
 **/
@Component
public class WindActurtor {
    @Autowired
    private Trigger trigger;

    @Resource
    private LimiterRecord limiterRecord;

    @SneakyThrows
    public Object windowLimiter(String namespace, String limitKey, LimiterBencher bencher, WrapLimiterRule wrapLimiterRule,
                                ProceedingJoinPoint joinPoint, boolean allowed, HttpServletResponse response) {
        Object[] args = joinPoint.getArgs();
        if (allowed) {
            bencher.setAllowed(true);
        } else {
            /**
             * half current limit
             */
            if (wrapLimiterRule.isTriggerLimit()) {
                bencher.setAllowed(false);
            }
            limiterRecord.store(wrapLimiterRule, bencher.getRecordKey(), limitKey);
            trigger.triggerLimiter(namespace, limitKey, joinPoint, response, bencher);
        }
        args[0] = bencher;
        return joinPoint.proceed(args);
    }


}
